package com.zhuiyun.project.api.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.caseImage.entity.CaseImage;
import com.zhuiyun.project.api.caseImage.mapper.CaseImageMapper;
import com.zhuiyun.project.api.coachmanagement.entity.CoachManagement;
import com.zhuiyun.project.api.coachmanagement.mapper.CoachManagementMapper;
import com.zhuiyun.project.api.course.entity.Course;
import com.zhuiyun.project.api.course.mapper.CourseMapper;
import com.zhuiyun.project.api.course.service.ICourseService;
import com.zhuiyun.project.api.memberUserManagement.entity.MemberUserManagement;
import com.zhuiyun.project.api.memberUserManagement.mapper.MemberUserManagementMapper;
import com.zhuiyun.project.api.plan.fitnessAction.entity.FitnessAction;
import com.zhuiyun.project.api.plan.fitnessAction.mapper.FitnessActionMapper;
import com.zhuiyun.project.api.plan.fitnessPlan.entity.FitnessPlan;
import com.zhuiyun.project.api.plan.fitnessPlan.mapper.FitnessPlanMapper;
import com.zhuiyun.project.api.plan.fitnessPlanAction.mapper.FitnessPlanActionMapper;
import com.zhuiyun.project.api.plan.fitnessSeries.entity.FitnessSeries;
import com.zhuiyun.project.api.plan.fitnessSeries.mapper.FitnessSeriesMapper;
import com.zhuiyun.project.api.plan.fitnessType.entity.FitnessType;
import com.zhuiyun.project.api.plan.fitnessType.mapper.FitnessTypeMapper;
import com.zhuiyun.project.api.reservation.entity.Reservation;
import com.zhuiyun.project.api.reservation.mapper.ReservationMapper;
import com.zhuiyun.project.api.reservation.mapper.TrainingTimeMapper;
import com.zhuiyun.project.api.venuemanagement.entity.VenueManagement;
import com.zhuiyun.project.api.venuemanagement.mapper.VenueManagementMapper;
import com.zhuiyun.project.api.vipPlan.entity.ActionCount;
import com.zhuiyun.project.api.vipPlan.entity.MemberPlan;
import com.zhuiyun.project.api.vipPlan.entity.MemberPlanAction;
import com.zhuiyun.project.api.vipPlan.mapper.ActionCountMapper;
import com.zhuiyun.project.api.vipPlan.mapper.MemberPlanActionMapper;
import com.zhuiyun.project.api.vipPlan.mapper.VipPlanMapper;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.constants.CommonConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName CourseController
 * @Description TODO 课程管理
 * @Author xy
 * @Date 2023/11/1 15:34
 **/
@RestController
@Api(tags = "课程管理")
@RequestMapping("/course")
@Slf4j
public class CourseController {

    @Resource
    CourseMapper courseMapper;

    @Resource
    ICourseService courseService;

    @Resource
    VenueManagementMapper venueManagementMapper;

    @Resource
    CoachManagementMapper coachManagementMapper;

    @Resource
    ReservationMapper reservationMapper;

    @Resource
    MemberUserManagementMapper memberUserManagementMapper;

    @Resource
    VipPlanMapper vipPlanMapper;

    @Resource
    FitnessTypeMapper fitnessTypeMapper;

    @Resource
    FitnessActionMapper fitnessActionMapper;

    @Resource
    ActionCountMapper actionCountMapper;

    @Resource
    FitnessPlanMapper fitnessPlanMapper;

    @Resource
    FitnessSeriesMapper fitnessSeriesMapper;

    @Resource
    MemberPlanActionMapper memberPlanActionMapper;

    @Resource
    CaseImageMapper caseImageMapper;

    /*
    * @Author xy
    * @Description todo 课程管理的分页查询筛选
    * @Date 2023/11/1 15:39
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param name 课程名称 status 课程状态 pageNum 当前页 pageSize 每页显示条数
    */
    @GetMapping("/page")
    @ApiOperation(value = "课程管理的分页查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "分页查询")
    public CommonResult findPage(@RequestParam(defaultValue = "") String name,
                                 @RequestParam(defaultValue = "") String coach,
                                 @RequestParam(defaultValue = "") String venueUniqueIdentifier,
                                 @RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        queryWrapper.eq("venue_unique_identifier", venueUniqueIdentifier);
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (!"".equals(coach)) {
            queryWrapper.eq("coach", coach);
        }
        IPage<Course> page = courseService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return CommonResult.ok(page);
    }

    /*
    * @Author xy
    * @Description todo 课程管理的新增修改
    * @Date 2023/11/2 10:40
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param course 课程实体类 file 课程图片
    */
    @PostMapping("/add")
    @ApiOperation(value = "课程管理的新增修改")
    @OptLog(modular = "课程管理", type = CommonConstants.ADD, describe = "新增修改")
    public CommonResult add( Course course, MultipartFile file) {
        boolean b = courseService.saveupdateCourse(course, file);
        if(b){
            return CommonResult.ok("操作成功");
        }else {
            return CommonResult.error("操作失败");
        }

    }

    /*
    * @Author xy
    * @Description todo 课程管理的修改状态
    * @Date 2023/11/6 8:42
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param course 课程实体类
    */
    @PostMapping("/modify")
    @ApiOperation(value = "课程管理的修改状态")
    @OptLog(modular = "课程管理", type = CommonConstants.UPDATE, describe = "修改状态")
    public CommonResult modify(@RequestBody Course course) {
        int i = courseMapper.updateById(course);
        if(i>0){
            return CommonResult.ok("操作成功");
        }else {
            return CommonResult.error("操作失败");
        }
    }

    /*
    * @Author xy
    * @Description todo 课程管理的删除
    * @Date 2023/11/6 9:15
    * @Return
    * @param
    */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "课程管理的删除")
    @OptLog(modular = "课程管理", type = CommonConstants.DELETE, describe = "删除")
    public CommonResult delete(@PathVariable Integer id) {
        Course course = courseMapper.selectById(id);
        // 把del_flag改为1
        course.setDelFlag("1");
        int i = courseMapper.updateById(course);
        if(i>0){
            return CommonResult.ok("操作成功");
        }else {
            return CommonResult.error("操作失败");
        }
    }

    /*
    * @Author xy
    * @Description todo 场馆信息的查询
    * @Date 2023/11/6 16:51
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param
    */
    @GetMapping("/venue")
    @ApiOperation(value = "场馆信息的查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "场馆信息的查询")
    public CommonResult venue() {
        QueryWrapper<VenueManagement> queryWrapper = new QueryWrapper<>();
        List<VenueManagement> venueManagements = venueManagementMapper.selectList(queryWrapper);
        return CommonResult.ok(venueManagements);
    }

    /*
    * @Author xy
    * @Description todo 教练信息的查询
    * @Date 2023/11/7 9:05
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param
    */
    @GetMapping("/coach")
    @ApiOperation(value = "教练信息的查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "教练信息的查询")
    public CommonResult coach(String venueUniqueIdentifier) {
        QueryWrapper<CoachManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("venue_unique_identifier", venueUniqueIdentifier);
        List<CoachManagement> coachManagements = coachManagementMapper.selectList(queryWrapper);
        return CommonResult.ok(coachManagements);
    }

    /*
    * @Author xy
    * @Description todo 课程信息查询id和name
    * @Date 2023/11/7 14:29
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param
    */
    @GetMapping("/idname")
    @ApiOperation(value = "课程信息查询id和name")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "课程信息查询id和name")
    public CommonResult idname() {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","name","status");
        List<Course> courses = courseMapper.selectList(queryWrapper);
        return CommonResult.ok(courses);
    }

    /*
    * @Author xy
    * @Description todo 课程信息全查（status为待预约的字段）
    * @Date 2023/11/13 18:52
    * @Return
    * @param
    */
    @GetMapping("/all")
    @ApiOperation(value = "课程信息全查")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "课程信息全查")
    public CommonResult all(Integer coachId, Integer memberId) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reservation_status", 0);
        queryWrapper.eq("coach_id", coachId);
        queryWrapper.eq("student_id", memberId);
        List<Reservation> reservations = reservationMapper.selectList(queryWrapper);

        for (Reservation reservation : reservations) {
            Integer courseId = reservation.getCourseId();
            MemberPlan memberPlan = vipPlanMapper.selectById(courseId);
            int planId = memberPlan.getPlanId();
            FitnessPlan fitnessPlan = fitnessPlanMapper.selectById(planId);
            reservation.setPlanName(fitnessPlan.getFitnessPlanName());

            Integer seriesId = fitnessPlan.getFitnessSeriesId();
            FitnessSeries fitnessSeries = fitnessSeriesMapper.selectById(seriesId);
            reservation.setSeriesName(fitnessSeries.getSeriesName());

            Integer coachId1 = reservation.getCoachId();
            CoachManagement coachManagement = coachManagementMapper.selectById(coachId1);
            reservation.setCoachName(coachManagement.getCoachName());
        }
        return CommonResult.ok(reservations);
    }

    /*
    * @Author xy
    * @Description todo 课程信息的全查（status为代训练的字段）
    * @Date 2023/11/14 15:19
    * @Return
    * @param
    */
    @GetMapping("/trained")
    @ApiOperation(value = "课程信息的全查")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "课程信息的全查")
    public CommonResult trained(Integer coachId, Integer memberId) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reservation_status", 1);
        queryWrapper.eq("coach_id", coachId);
        queryWrapper.eq("student_id", memberId);
        List<Reservation> reservations = reservationMapper.selectList(queryWrapper);

        for (Reservation reservation : reservations) {
            Integer courseId = reservation.getCourseId();
            MemberPlan memberPlan = vipPlanMapper.selectById(courseId);
            int planId = memberPlan.getPlanId();
            FitnessPlan fitnessPlan = fitnessPlanMapper.selectById(planId);
            reservation.setPlanName(fitnessPlan.getFitnessPlanName());

            Integer seriesId = fitnessPlan.getFitnessSeriesId();
            FitnessSeries fitnessSeries = fitnessSeriesMapper.selectById(seriesId);
            reservation.setSeriesName(fitnessSeries.getSeriesName());

            Integer coachId1 = reservation.getCoachId();
            CoachManagement coachManagement = coachManagementMapper.selectById(coachId1);
            reservation.setCoachName(coachManagement.getCoachName());
        }
        return CommonResult.ok(reservations);
    }

    /*
    * @Author xy
    * @Description todo 预约用户信息查询
    * @Date 2023/12/5 9:11
    * @Return
    * @param
    */
    @GetMapping("/member")
    @ApiOperation(value = "预约用户信息查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "预约用户信息查询")
    public CommonResult member(String phone) {
        QueryWrapper<MemberUserManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_user_phone", phone);
        List<MemberUserManagement> memberUserManagements = memberUserManagementMapper.selectList(queryWrapper);
        return CommonResult.ok(memberUserManagements);
    }

    /*
    * @Author xy
    * @Description todo 课程信息的全查（status为已完成的字段）
    * @Date 2023/11/14 15:20
    * @Return
    * @param
    */
    @GetMapping("/progress")
    @ApiOperation(value = "课程信息的全查")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "课程信息的全查")
    public CommonResult progress(Integer coachId, Integer memberId) {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reservation_status", 2);
        queryWrapper.eq("coach_id", coachId);
        queryWrapper.eq("student_id", memberId);
        //倒序
        queryWrapper.orderByDesc("reservation_time");
        List<Reservation> reservations = reservationMapper.selectList(queryWrapper);

        for (Reservation reservation : reservations) {
            Integer courseId = reservation.getCourseId();
            MemberPlan memberPlan = vipPlanMapper.selectById(courseId);
            int planId = memberPlan.getPlanId();
            FitnessPlan fitnessPlan = fitnessPlanMapper.selectById(planId);
            reservation.setPlanName(fitnessPlan.getFitnessPlanName());

            Integer seriesId = fitnessPlan.getFitnessSeriesId();
            FitnessSeries fitnessSeries = fitnessSeriesMapper.selectById(seriesId);
            reservation.setSeriesName(fitnessSeries.getSeriesName());

            Integer coachId1 = reservation.getCoachId();
            CoachManagement coachManagement = coachManagementMapper.selectById(coachId1);
            reservation.setCoachName(coachManagement.getCoachName());
        }
        return CommonResult.ok(reservations);
    }

    /*
    * @Author xy
    * @Description todo 取消预约
    * @Date 2023/11/22 10:58
    * @Return
    * @param
    */
    @PostMapping("/cancel")
    @ApiOperation(value = "取消预约")
    @OptLog(modular = "课程管理", type = CommonConstants.UPDATE, describe = "取消预约")
    public CommonResult cancel(@RequestParam Integer courseId,
                               @RequestParam Integer Id,
                               @RequestParam Integer userId) {
        // 根据当前登录的教练Id查询Course表里对应的课程信息然后修改状态为待预约
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("coach_id", Id);
        queryWrapper.eq("id", courseId);
        List<Course> courses = courseService.list(queryWrapper);
        if (courses != null && !courses.isEmpty()) {
            // 如果找到匹配的课程记录
            Course course = courses.get(0); // 假设只有一条记录，你可以根据实际情况处理
            course.setStatus("0"); // 修改状态为待训练
            courseService.updateById(course); // 更新课程记录
        }
        List<Reservation> resultList = reservationMapper.selectList(new QueryWrapper<Reservation>().eq("student_id", userId).eq("course_id", courseId));
        // 根据学员id查询预约表里的记录
        if(resultList != null && !resultList.isEmpty()){
            // 如果找到匹配的预约记录
            Reservation reservation = resultList.get(0);
            // 删除预约记录
            reservationMapper.deleteById(reservation.getId());
            return CommonResult.ok("取消成功");
        } else {
            return CommonResult.error("取消失败");
        }
    }

    /*
    * @Author xy
    * @Description todo 预约查询（只查id）
    * @Date 2023/11/22 15:04
    * @Return
    * @param
    */
    @GetMapping("/appointmentID")
    @ApiOperation(value = "预约查询（只查id）")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "预约查询（只查id）")
    public CommonResult appointmentID() {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        List<Reservation> reservations = reservationMapper.selectList(queryWrapper);
        return CommonResult.ok(reservations);
    }

    /*
    * @Author xy
    * @Description todo 查询课程图片
    * @Date 2023/11/28 9:56
    * @Return
    * @param
    */
    @GetMapping("/listimg")
    @ApiOperation(value = "查询课程图片")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "查询课程图片")
    public CommonResult listimg() {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("images");
        List<Course> courses = courseMapper.selectList(queryWrapper);
        return CommonResult.ok(courses);
    }

    /*
    * @Author xy
    * @Description todo 教练电话查询
    * @Date 2023/12/5 9:58
    * @Return
    * @param
    */
    @GetMapping("/coachphone")
    @ApiOperation(value = "教练电话查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "教练电话查询")
    public CommonResult coachphone(Integer coachId) {
        QueryWrapper<CoachManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", coachId);
        List<CoachManagement> coachManagements = coachManagementMapper.selectList(queryWrapper);
        return CommonResult.ok(coachManagements);
    }

    /*
    * @Author xy
    * @Description todo 课程安排查询
    * @Date 2023/12/5 10:59
    * @Return
    * @param
    */
    @GetMapping("/part")
    @ApiOperation(value = "训练部位查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "训练部位查询")
    public CommonResult part(Integer courseId) {
            QueryWrapper<MemberPlanAction> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("plan_id", courseId);
            List<MemberPlanAction> memberPlanActions = memberPlanActionMapper.selectList(queryWrapper1);
            for (MemberPlanAction memberPlanAction : memberPlanActions) {
                // 根据计划动作id查询动作id
                Integer actionId = memberPlanAction.getActionId();
                Integer id = memberPlanAction.getId();
                FitnessAction fitnessAction = fitnessActionMapper.selectById(actionId);
                QueryWrapper<CaseImage> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("action_id", id);
                List<CaseImage> caseImages = caseImageMapper.selectList(queryWrapper2);
                for(CaseImage ins:caseImages){
                    memberPlanAction.setActionImg(ins.getActionImage());
                }
                // 根据动作id查询动作类型id
                Integer fitnessTypeId = fitnessAction.getFitnessTypeId();
                FitnessType fitnessType = fitnessTypeMapper.selectById(fitnessTypeId);
                memberPlanAction.setTypeName(fitnessType.getFitnessTypeName());
                memberPlanAction.setActionName(fitnessAction.getFitnessActionName());
            }
        return CommonResult.ok(memberPlanActions);
    }

    /*
    * @Author xy
    * @Description todo 动作详细查询
    * @Date 2023/12/5 19:07
    * @Return
    * @param
    */
    @GetMapping("/action")
    @ApiOperation(value = "动作详细查询")
    @OptLog(modular = "课程管理", type = CommonConstants.SELECT, describe = "动作详细查询")
    public CommonResult action(Integer actionId) {
        QueryWrapper<ActionCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_action_id", actionId);
        List<ActionCount> actionCounts = actionCountMapper.selectList(queryWrapper);
        return CommonResult.ok(actionCounts);
    }


}
